import {
	Component
} from 'react';
import {
	Group,
	Collapse,
	Boxs,
	Avatar,
	Button,
	Dialog,
	ActionSheet,
} from 'saltui';
import AngleRight from 'salt-icon/lib/AngleRight';
const {
	IconButton
} = Button;
const {
	HBox,
	Box,
	VBox
} = Boxs;
import PageController from 'pages/home';
const Panel = Collapse.Panel;
import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap,
	TextareaField
} from '../../../app/variables';
import DB from '../../../app/db';
import BoardChild from './boardChild';

let ActionSheetButton;
export default class PageHome extends Component {

	constructor(props) {
		super(props);
		this.state = {
			activeIndex: 2,
			isShow:false,
			key:[],
			tree: [],
			boardArray:[],
			option:[],
		}

		this.OPERATE = [{
			name: '查看详情',
			code: 'detail'
		}];
		 dd.biz.navigation.setTitle({
      		title: '版块导航',
		    onSuccess: function (result) {
		    },
     		 onFail: function () {
      		}
    		});
	}

	componentWillMount() {
		this.queryTypeBoardTree();
		//this.dislodgeActionSheet();
		this.judgeOperate();
		this.dd();
		Dialog.hide();
	}
	componentWillUnmount(){
		if(ActionSheetButton){
	      ActionSheetButton.close();
	    }
	}
	judgeOperate() {
		let option = this.generateIndependentOptions();
		this.pushInIndependentOptions(option, 'detail');
		this.setState({
			option: option
		});
	}

	dd(){
      var u = navigator.userAgent;
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if(isAndroid==true){

           document.addEventListener('backbutton', function(e) {
            $('.t-popup-mask').trigger('click');
            e.preventDefault();
           });
      }else if(isiOS==true){

          dd.biz.navigation.setLeft({
              control: true,//是否控制点击事件，true 控制，false 不控制， 默认false
              text: '',//控制显示文本，空字符串表示显示默认文本
              onSuccess : function(result) {
                $('.t-popup-mask').trigger('click');
                $('.t-popup-mask').trigger('click');
                backPage();
              },
              onFail : function(err) {}
          });
      }
    }

	generateIndependentOptions() {
		return new Array();
	}

	pushInIndependentOptions(options, code) {

		if (options instanceof Array) {
			let n = this.acquireOptionWithName(code);
			options.push(n);
		}
		return options;
	}

	acquireOptionWithName(n) {
		let s;
		this.OPERATE.map((item, index) => {
			if (item.code == n) {
				s = item;
				return item;
			}
		});
		return s;
	}

	handleOperateClick(board) {
	 	let t = this;
		ActionSheetButton = ActionSheet.show({
			options: t.acquireIndependentOptionsName(t.state.option),
			maskClosable: true,
		}, t.clickOperateItem.bind(t, t.state.option,board.id));
	}
/**
	 * 获取独立空间中操作选项的名称
	 * @param  {[type]}
	 * @return {[type]}
	 */
	acquireIndependentOptionsName(options) {
		let names = [];
		if (options && options.length > 0) {
			options.map((item, index) => {
				names.push(item.name);
			});
		}
		return names;
	}

	clickOperateItem(option,id, index) {
		if (index == -1) {
			return;
		}
		let opt = option[index];
		 if (opt.code == 'detail') {
		 	location.hash = 'board/view/' + id;
			//pageSkip('static/officeding/forum/dist/index.html', '#/board/view/' + id);
		} 
	}

     // 板块导航查看更多点击
    onChange = (e) => {
		console.log('onChange: ', e);
		if (e == "a") {
		  this.setState({
			isShow: true
		  })
		} else if (e != "a") {
		  this.setState({
			isShow: false
		  })
		}
    }

	queryTypeBoardTree() {
		let param = {
		};
		DB.ForumModuleAPI.getBoardTree(param).then((content) => {
			let key = [];
			content.map((item, index) => {
				key.push(item.id);
			});
			this.setState({
				key: key,
				tree: content
			});
		}).then((error) => {

		});
	}

	leaveClick(board) {
		let boardPicId = "";
		if(board.attIdJson!="" && board.attIdJson!=null){
			boardPicId = board.attIdJson[0].id;
		}
		location.href = '#/board/page/' + board.id +'/'+ board.replyCount + '/' + board.postCount + '/' + board.name + '/' +boardPicId;
		//pageSkip('static/officeding/forum/dist/index.html', '#/board/page/' + board.id);
	}

	generateTreeHtml(tree) {
		let header1 = <span className="t-FS16 t-FCddblue t-DB" style={{textAlign:'center'}} >收起</span> ;
		let header2 = <span className="t-FS16 t-FCddblue t-DB" style={{textAlign:'center'}} >查看全部</span> ;
		let html="";
		var itemList = "";
		let t = this;
		let nodataFlag = 0;
		if (tree && tree.length > 0) {
			html = tree.map(function(item,index){
				if(item.boardArray == null){
					nodataFlag = nodataFlag +1;
				}
				return (
					<div className= 't-BCf color-list' >
						<div className={item.boardArray==null?"t-DN":""}>
						<HBox className="dd-top-border t-PL16  t-PT18 t-PB12 t-H46 color-border-left" vAlign="center">
							<Box className="t-FC3 t-FS16 t-omit t-PR4 t-PR" flex={1} style={{ lineHeight:"20px",top:'-1px' }}>{item.name}</Box>
						</HBox>
						</div>
						<BoardChild 
							boardArray={item.boardArray} 
							handleOperateClick={(value) => {t.handleOperateClick(value);}}
							leaveClick={(value) => {t.leaveClick(value);}}/>
					</div>
				)		
		    }.bind(this));
		}
		//if(nodataFlag == tree.length)
	    /*else{
			html = (<div className="dd-nodata">
			<VBox hAlign="center">
				<Box style={{ marginTop: '70%' }}>
					<img src={nodataIcon} style={{ width: 60 + 'px' }} />
				</Box>
				<Box className="dd-nodata-text t-FC6">
					暂无数据
				</Box>
			</VBox>
		</div>)
		}*/
		return html;
	}

	render() {
		const header = <span className="t-FS16 t-FCddblue t-DB" style={{textAlign:'center'}}>查看全部</span>;
        const t = this;
        const onChange = (activeIndex) => {
        // 这里是触发每个item之后的回调，会返回当前点击的item的index 值
        console.log(activeIndex);
        this.setState({ activeIndex: activeIndex });

        };

		let key = this.state.key;
		return (
			<div className="t-PB44 forums-index color-index">
				{this.generateTreeHtml(this.state.tree)}
				<PageController activeIndex={1}/>	
			</div>	
		);
	}
}